<template>
  <div id="avatar-box">
    <el-avatar
      :size="100"
      :src="currentUser.imagePath"
      @error="errorHandler"
    >
      <img src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png" alt="">
    </el-avatar>
    <el-upload
      :action="httpUrl"
      :headers="{token: currentUser.token}"
      accept=".jpg, .jpeg, .png"
      :before-upload="beforeUpload"
      :show-file-list="false"
      :on-success="handleSuccess"
    >
      <el-button type="primary" plain>修改头像</el-button>
    </el-upload>
  </div>
</template>

<script>

import {mapState} from "vuex";
import {commonMixin} from "@/mixin";

export default {
  name: "AvatarShow",
  mixins: [commonMixin],
  data() {
    return {
      httpUrl: 'http://' + this.$store.state.httpHost + ':8080/files',
    }
  },
  computed: {
    ...mapState(['currentUser']),
  },
  methods: {
    errorHandler() {
      return true;
    },
    beforeUpload(file) {
      const isImage = file.type === '.jpg' || '.png' || '.jpeg';
      const isLt5M = file.size / 1024 / 1024 < 5;

      if (!isImage) {
        this.$message.error('上传头像图片只能是 JPG/PNG/JPEG 格式!');
      }
      if (!isLt5M) {
        this.$message.error('上传头像图片大小不能超过 5MB!');
      }
      return isImage && isLt5M;
    },
    // 成功
    handleSuccess(resp) {
      const fileUrl = resp.data;
      const user = this.currentUser;
      const url = '/users/imagePath'
      user.imagePath = fileUrl;

      this.updateUser(url, user);
    },
    // 更新数据
    updateUser(url, bodyData) {
      this.axios.put(url, bodyData).then(resp => {
        if (resp.code === 200) {
          this.$message({
            type: "success",
            message: '修改成功',
            center: true,
          });
          // 上传成功
          this.updateLocalStorageUser(resp.data);
        } else {
          this.$message({
            type: "error",
            message: '头像更新失败',
            center: true,
          });
        }
      })
    }
  }
}
</script>

<style scoped>
#avatar-box {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-around;

  * {
    margin: 5px;
  }
}
</style>